package com.sea.base.floating

import android.app.Activity
import android.app.Application
import android.view.View
import androidx.annotation.MainThread
import androidx.collection.ArrayMap
import com.sea.base.ext.global.registerActivityLifecycleCallbacks
import com.sea.base.ext.global.singleApplication
import com.sea.base.ext.view.asViewGroup
import com.sea.base.ext.view.decorViewGroup
import com.sea.base.ext.view.parentOrNull
import com.sea.base.utils.ActivityStackManager

object GlobalFloatingUtil {
    private val floatingMap = ArrayMap<View, Application.ActivityLifecycleCallbacks>()

    @MainThread
    fun showAppFloating(view: View) {
        floatingMap[view]?.let { return }
        ActivityStackManager.getCurrentActivity()?.let { checkAdd(it, view) }
        val callbacks = singleApplication.registerActivityLifecycleCallbacks(onResumed = {
            checkAdd(it, view)
        })
        floatingMap[view] = callbacks
    }

    private fun checkAdd(it: Activity, view: View) {
        if (it !is IDoNotDisturb) {
            addView(view, it)
        }
    }

    @MainThread
    fun hideAppFloating(view: View) {
        floatingMap[view]?.let { singleApplication.unregisterActivityLifecycleCallbacks(it) }
        floatingMap.remove(view)
        view.parentOrNull?.removeView(view)
    }

    private fun addView(view: View, activity: Activity) {
        val viewParent = view.parent?.asViewGroup()
        val decorVg = activity.window.decorViewGroup
        if (viewParent != decorVg) {
            viewParent?.removeView(view)
            decorVg.addView(view)
        }
    }
}